<?php

namespace app\common\service;

use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\order\logic\OrderShipLogic;
use app\order\logic\OrderWhLogic;
use app\order\model\SkuWeightSize;
use app\common\service\ConstantOrderService;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Config;
use think\facade\Db;

/*
 *  金蚁api:http://qqwy.3wms.com/Pages/DocApi/HomePage.html
 */

class YiJTApiService
{
    protected $url = null;

    public function __construct()
    {
        $this->url = Config('Logisticskey.YiJT.url');
    }



    /**
     * @param $order
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @desc  生成订单
     */
    public function createOrder($order)
    {
        //日志
        $exist_ship = Db::name('order_ship')->where('order_id', $order['order_id'])->find();
        if(!$exist_ship){
            Db::name('order_ship')->insert([
                    'order_id'        =>$order['order_id'],
                    'shop_id'         =>$order['shop_id'],
                    'warehouse_id'    =>$order['warehouse_id'],
                    'status'          =>0,
                    'time'            =>time(),
                    'tracking_number' =>"",
                    'msg'             =>"初始",
                    'type'            =>1,
                ]
            );
        }

        htmlLog(['order'=>$order],OPERATE_LOG . date('Ym') . '/createOrder/' . date('Ymd') . '.txt');
        $return = [
            'order_id'     => $order['order_id'],
            'shop_id'      => $order['shop_id'],
            'warehouse_id' => $order['warehouse_id'],
            'data'         => '',
            'return0'      => '',
            'return1'      => '',
        ];

        $JsonData = self::buildJsonData($order);

        //sku信息组装  2024-05-10 查看是否拆分sku
        $exist_split_sku = Db::name('order_split_ship')->where(['order_id'=>$order['order_id']])->find();
        if($exist_split_sku){
            $skuInfos   = $order['skuinfo'];
            $skuInfos   = explode(',',$skuInfos);
        }else{
            $skuInfos   = Db::name('order_info')->where('order_id', $order['order_id'])->column('seller_sku');
        }
        $orderDetail_arr = $arr = $OrderDetail = [];

        foreach($skuInfos as $v){
            if($exist_split_sku){
                $orderDetail_arr[] = get_seller_sku_change($v);
            }else{
                $orderDetail_arr[] = get_seller_sku($v);
            }
        }

        if(!$orderDetail_arr)  return true;

        //数组整合
        foreach($orderDetail_arr as $v){
            if(isset($v[0]) && is_array($v[0])){
                foreach($v as $value){
                    $arr[] = $value;
                }
            }else{
                    $arr[] = $v;
            }
        }

        foreach($arr as $v){
            $sample_sku = self::get_sample_sku($v['sku']);
            $OrderDetail[] = [
                'sku'   => $sample_sku,
                'nums'=> $v['qtyOrdered'],
            ];
        }
        $OrderDetail                 = self::getQtyOrdered($OrderDetail);
        $JsonData["deliver_products"] = $OrderDetail;
        //渠道规则
        $order['postal_code'] = $order['postal_code'] ?? '';
        $zip_code = Db::name('zip_code')->where('zipcode',$order['postal_code'])->find();
        $zip_code['chqd'] = $zip_code['chqd'] ?? '';
        $zip_code['ck_nums'] = $zip_code['ck_nums'] ?? '';
        if(!empty($zip_code['chqd'])){
            $zip_code['chqd'] = trim($zip_code['chqd']);
        }else{
            $zip_code['chqd'] = 'HY-USPS-NY';
        }
        if(!empty($zip_code['ck_nums'])){
            $zip_code['ck_nums'] = trim($zip_code['ck_nums']);
        }else{
            $zip_code['ck_nums'] = 'DYY-NY';
        }
        $JsonData["chqd"]  = $zip_code['chqd'];
        $JsonData["ck_nums"]  = $zip_code['ck_nums'];
        //渠道规则

        //deliver_no
        // $JsonData['deliver_no'] = $JsonData['deliver_no'] . rand(11,99);

        $JsonDatas[] = $JsonData;
        // halt($JsonDatas);
        
        //订单数据推送到易境通 2024-12-07
        $url = $this->url . Config('Logisticskey.YiJT.add_order');
        htmlLog(['url'=>$url,'params'=>$JsonDatas,'order_id'=>$order['order_id']],OPERATE_LOG . date('Ym') . '/createOrder/' . date('Ymd') . '.txt');
        $response = HttpUtil::postUrlYiJT($url, $JsonDatas);
        // halt($response);
        
        $result   = json_decode($response, true);
        htmlLog(['response'=>$result,'order_id'=>$order['order_id']],OPERATE_LOG . date('Ym') . '/createOrder/' . date('Ymd') . '.txt');
        //返回结果处理;
        if (isset($result['error']) && $result['error'] == "T") {
            self::handleSuccessShipping($response,$order,$JsonDatas);
        } else {
            self::handleFailedShipping($order, $response,$return);
        }
        return true;
    }
    

    

    /**
     * @desc 处理发货成功的情况
     * @date  2024-03-30
     * @author luckyXiong
     */
    private function handleSuccessShipping($response,$order,$orderData=[])
    {
        $result   = json_decode($response, true);
        $return['code']    = 3;
        $return['msg']     = $order['shipping_type'] == 'TIKTOK' ?  "操作成功" : "等待回传物流单号";
        $return['return0'] = $response;
        $return['data']    = '';
        $return['order_id']    = $order['order_id']??'';
        $return['shop_id']     = $order['shop_id']??'';
        $tracking_number   = '';
        //有跟踪号代表发货了
        $msg                            = '都要赢海外仓，已发货';
        $status                         = 3;

        $exist_ship = Db::name('order_ship')->where('order_id', $order['order_id'])->find();
        if(!$exist_ship){
            Db::name('order_ship')->insert([
                    'order_id'        =>$order['order_id'],
                    'shop_id'         =>$order['shop_id'],
                    'warehouse_id'    =>$order['warehouse_id'],
                    'status'          =>$status,
                    'time'            =>time(),
                    'tracking_number' =>$tracking_number,
                    'msg'             =>$msg,
                    'type'            =>$order['type']
                ]
            );
        }else{
            Db::name('order_ship')->where('order_id', $order['order_id'])->update([
                    'warehouse_id'     =>$order['warehouse_id'],
                    'status'           =>$status,
                    'time'             =>time(),
                    'tracking_number'  =>$tracking_number,
                    'msg'              =>$msg,
                ]
            );
        }

        Db::name('order')->where('order_id', $order['order_id'])->update([
            'send_status'=>1
        ]);


        //更新仓库ID
        $exist_split_ship = Db::name('order_split_ship')->where([
            'order_id'  =>$order['order_id'],
            'seller_sku'=>$order['skuinfo'],
        ])->find();

        if($exist_split_ship){
            Db::name('order_split_ship')
                ->where([
                    'order_id'  =>$order['order_id'],
                    'seller_sku'=>$order['skuinfo'],
                ])->update(
                    [
                        'warehouse_id' =>$order['warehouse_id'],
                        'status'       =>1,
                        'update_time'  =>date("Y-m-d H:i:s", time()),
                    ]);
        }
        OrderShipLogic::insertOrderShipLog($return);
    }

    /**
     * @desc 处理发货失败的情况
     * @date  2024-03-30
     * @author luckyXiong
     */
    private function handleFailedShipping($order, $response,$return=[])
    {
        $result            = json_decode($response, true);
        $result['content'] = $result['content'] ?? '无';
        
        $return['code']    = 2;
        $return['msg']     = "错误：" . $result['content'] ?? "订单发货失败";
        $return['return0'] = $response;

        $updateShip['status'] = 2;
        $updateShip['time']   = time();
        $updateShip['msg']    = "错误：" . $result['content'] ?? "订单发货失败";
        $updateShip['warehouse_id'] = $order['warehouse_id'];

        $exist_ship = Db::name('order_ship')->where('order_id',$order['order_id'])->find();
        if(!$exist_ship){
            Db::name('order_ship')->insert([
                'order_id'    =>$order['order_id'],
                'shop_id'     =>$order['shop_id'],
                'warehouse_id'=>$order['warehouse_id'],
                'status'      =>2,
                'time'        =>time(),
                'msg'         =>$response,
                'type'        =>$order['type'],
            ]);
        }else{
            //异常重发页面失败了才改为已处理
            if($order['fail_status']==6){
                $updateShip['status'] = 5; //失败改为已处理
            }
            if (strpos($updateShip['msg'], '订单已存在') !== false) {
                $updateShip['status'] = 3;
            }
            Db::name('order_ship')->where('order_id', $order['order_id'])->update($updateShip);
        }


        //包含字符串
        if (strpos($updateShip['msg'], '订单已存在') !== false) {
            Db::name('order')->where('order_id', $order['order_id'])->update([
                'send_status'=>2
            ]);
        }else{
            Db::name('order')->where('order_id', $order['order_id'])->update([
                'send_status'=>0
            ]);
        }
        
        OrderShipLogic::insertOrderShipLog($return);
    }

    
    /**
     * @desc   匹配获取可以发货的库存数据
      * @date  2024-12-07
     * @author zhangheng
     * @title  尾部处理
     */
    public function get_sample_sku($sku=''){
        $sku_info = explode('-',$sku);
        $last     = $sku_info[2]??'';
        if($last=='XL/2XL'){
            $last = 'XL';
        }
        if($last=='3XL/4XL'){
            $last = '3XL';
        }

        if($last=='4XL/5XL'){
            $last = '4XL';
        }

        if($last=='5XL/6XL'){
            $last = '5XL';
        }

        if($last=='6XL/7XL'){
            $last = '6XL';
        }

        if($last=='XS/S'){
            $last = 'S';
        }
        if($last=='M/L'){
            $last = 'M';
        }
        $number = $sku_info[3]??0;
        if((int)$number>10){
            return  $sku_info[0].'-'.$sku_info[1].'-'.$last.'-'.$number;
        }
        if(empty($last)){
            return  $sku_info[0].'-'.$sku_info[1];
        }
        return  $sku_info[0].'-'.$sku_info[1].'-'.$last;
    }


    
    
    /**
     * @desc 数据统计
     * @date 2024-02-22
     */
    public function getQtyOrdered($info)
    {
        $outputArray = [];
        foreach ($info as $item) {
            $sku = $item['sku'];
            if (isset($outputArray[$sku])) {
                $outputArray[$sku]['nums'] += $item['nums'];
            } else {
                $outputArray[$sku] = $item;
            }
        }
        return array_values($outputArray);
    }


    /**
     * @desc  构建 JsonData返货参数处理
     * @date  2024-12-07
     * @author zhangheng
     */
    public function buildJsonData($order=[]){
        $JsonData = [];
        $JsonData['zip'] = $order['postal_code'];
        $JsonData['country'] = "美国";
        $JsonData['deliver_products'] = [];
        $JsonData['address'] = $order['address_detail'];
        $JsonData['city'] = $order['state'];
        $JsonData['district'] = $order['city'];
        $JsonData['deliver_no'] = $order['order_id'];
        $JsonData['mobile'] = $order['phone_number'];
        $JsonData['phone'] = $order['phone_number'];
        $JsonData['ck_nums'] = "";
        $JsonData['token'] = Config('Logisticskey.YiJT.token');
        $JsonData['chqd'] = "";
        $JsonData['contact'] = $order['name'];
        $JsonData['email'] = $order['buyer_email'];
        $JsonData['platform'] = "tiktok";
        // $JsonData['waybill'] = "";//自提获得自己提供面单使用的快递单号
        // $JsonData['pda_url'] = "";//面单链接,Pdf格式
        // 其他逻辑处理...
        return $JsonData;
    }


}
